package api

import (
	"os"
	"strings"

	"github.com/spf13/viper"
)

var (
	defaultConfig = map[string]interface{}{
		"server.read_timeout":  5,
		"server.write_timeout": 30,
		"server.handler_pool":  5000,
		"server.addr":          ":9001",
		"server.schema":        "http", // http, https, unix
		"server.pattern":       "/api",
		"apinonce.disabled":    false,
		"apisign.disabled":     false,
	}
)

func loadConfigFromFile(filePath string) (*viper.Viper, error) {

	c := viper.New()
	for k, v := range defaultConfig {
		c.SetDefault(k, v)
	}

	return LoadConfigFromPath(c, filePath)

}

func LoadConfigFromPath(c *viper.Viper, path string) (config *viper.Viper, err error) {
	fd, err := os.OpenFile(path, os.O_RDONLY, 0644)
	if err != nil {
		return nil, err
	}
	defer fd.Close()

	c.SetConfigType("yaml")
	err = c.ReadConfig(fd)

	return c, err
}

func LoadConfigFromEnv(c *viper.Viper, prefix string) *viper.Viper {

	c.SetEnvPrefix(prefix)
	c.AutomaticEnv()
	replacer := strings.NewReplacer(".", "_")
	c.SetEnvKeyReplacer(replacer)
	return c
}
